<template>
  <div
    class="draggable-item"
    :class="{ 'dragging': isDragging, 'disabled': disabled }"
    :draggable="!disabled"
    @dragstart="handleDragStart"
    @dragend="handleDragEnd"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
  >
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { soundManager } from '@/utils/sound'

interface Props {
  itemId: string
  itemValue: any
  itemType?: string
  disabled?: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  dragStart: [data: { id: string; value: any; type?: string }]
  dragEnd: []
}>()

const isDragging = ref(false)
let touchStartX = 0
let touchStartY = 0

function handleDragStart(e: DragEvent) {
  if (props.disabled) return

  isDragging.value = true
  soundManager.playDrag()

  const data = {
    id: props.itemId,
    value: props.itemValue,
    type: props.itemType
  }

  e.dataTransfer!.effectAllowed = 'move'
  e.dataTransfer!.setData('application/json', JSON.stringify(data))

  emit('dragStart', data)
}

function handleDragEnd() {
  isDragging.value = false
  emit('dragEnd')
}

// 触摸事件支持（移动端）
function handleTouchStart(e: TouchEvent) {
  if (props.disabled) return

  const touch = e.touches[0]
  touchStartX = touch.clientX
  touchStartY = touch.clientY

  isDragging.value = true
  soundManager.playDrag()

  const data = {
    id: props.itemId,
    value: props.itemValue,
    type: props.itemType
  }

  emit('dragStart', data)
}

function handleTouchMove(e: TouchEvent) {
  if (props.disabled || !isDragging.value) return
  e.preventDefault()
}

function handleTouchEnd(e: TouchEvent) {
  if (props.disabled) return

  isDragging.value = false
  emit('dragEnd')

  // 检测触摸结束位置是否在放置区域
  const touch = e.changedTouches[0]
  const element = document.elementFromPoint(touch.clientX, touch.clientY)

  if (element && element.classList.contains('drop-zone')) {
    const event = new CustomEvent('touchdrop', {
      detail: {
        id: props.itemId,
        value: props.itemValue,
        type: props.itemType
      }
    })
    element.dispatchEvent(event)
  }
}
</script>

<style scoped>
.draggable-item {
  cursor: grab;
  user-select: none;
  touch-action: none;
  transition: transform 0.2s, opacity 0.2s;
}

.draggable-item:active {
  cursor: grabbing;
}

.draggable-item.dragging {
  opacity: 0.5;
  transform: scale(1.1);
}

.draggable-item.disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.draggable-item:not(.disabled):hover {
  transform: scale(1.05);
}
</style>
